const express = require('express');
const fs = require('fs');
const path = require('path');

const app = express();

function getFilePath(fileName) {
  return path.join(__dirname, `./data/${fileName}`);
}

app.use(express.static('public'));

app.all('*', (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); 
  res.header('Access-Control-Allow-Metheds', 'PUT, POST, GET, DELETE, OPTIONS');
  res.header('X-Powered-By', 'nodejs'); 
  res.header('Content-Type', 'application/json;charset=utf-8');
  next();
})

app.get('/', (req, res) => {
  const filePath = path.join(__dirname, './public/index.html');
  fs.readFile(filePath, (err, data) => {
    if (err) {
      res.send('文件读取失败');
    } else {
      res.header('Content-Type', 'text/html;charset:utf-8');
      res.send(data);
    }
  })
})

app.get('/api/provinces', (req, res) => {
  const filePath = getFilePath('provinces.json');
  fs.readFile(filePath, (err, data) => {
    if (err) {
      res.send('文件读取失败');
    } else {
      res.send(data);
    }
  });
});

app.get('/api/cities/:provinceCode', (req, res) => {
  const { provinceCode } = req.params;
  const filePath = getFilePath('cities.json');
  fs.readFile(filePath, (err, data) => {
    if (err) {
      res.send('文件读取失败');
    } else {
      const cities = JSON.parse(data);
      const result = cities.filter(item => item.provinceCode === provinceCode);
      res.json(result);
    }
  });
});

app.get('/api/areas/:cityCode', (req, res) => {
  const { cityCode } = req.params;
  const filePath = getFilePath('areas.json');
  fs.readFile(filePath, (err, data) => {
    if (err) {
      res.send('文件读取失败');
    } else {
      const areas = JSON.parse(data);
      const result = areas.filter(item => item.cityCode === cityCode);
      res.json(result);
    }
  });
});

app.get('/api/streets/:areaCode', (req, res) => {
  const { areaCode } = req.params;
  const filePath = getFilePath('streets.json');
  fs.readFile(filePath, (err, data) => {
    if (err) {
      res.send('文件读取失败');
    } else {
      const streets = JSON.parse(data);
      const result = streets.filter(item => item.areaCode === areaCode);
      res.json(result);
    }
  });
});

app.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});
